package convert

import (
	"encoding/json"
	"time"

	"google.golang.org/protobuf/encoding/protojson"
	"google.golang.org/protobuf/proto"
)

// StrTime 将时间戳转成字符串
func StrTime(timestamp int64, timeLayout string) string {
	if timestamp == 0 {
		return ""
	}
	return time.Unix(timestamp, 0).Format(timeLayout)
}

// UnixTime 将字符串转成时间戳
func UnixTime(timeStr, layout string) int64 {
	date, err := time.ParseInLocation(layout, timeStr, time.Local)
	if err != nil {
		return 0
	}
	return date.Unix()
}

// ProtoToJson 转换proto为json string
func ProtoToJson(m proto.Message) string {
	d, _ := protojson.MarshalOptions{EmitUnpopulated: true}.Marshal(m)
	return string(d)
}

// JsonToProto 转换json string为proto
func JsonToProto(d string, m proto.Message) {
	protojson.UnmarshalOptions{DiscardUnknown: true}.Unmarshal([]byte(d), m)
}

// StructToJson 转换struct为json string
func StructToJson(data interface{}) string {
	b, _ := json.Marshal(data)
	return string(b)
}

// JsonToStruct 转换json string为struct，忽略转换错误
func JsonToStruct(data string, v interface{}) {
	json.Unmarshal([]byte(data), v)
}
